package org.zhangxf.service;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @AUTHOR zhangxf
 * @CREATE 2020-03-17 00:39
 */
public class NettyChatServerHandler extends SimpleChannelInboundHandler<String> {

    //获取ChannelGroup，里面存放所有的客户端channel，当有请求链接时，把当前的channel放入ChannelGroup中
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    //private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 一旦建立链接，该方法第一个被调用
     * 要把该channel添加进channelGroup
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[客户端]" + channel.remoteAddress() + "加入群聊\n");
        channelGroup.add(channel);
        System.out.println("[客户端]" + channel.remoteAddress() + "加入群聊\n");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        Channel channel = ctx.channel();

        channelGroup.forEach(ch -> {
            System.out.println(ch.equals(channel));
            //通知非当前用户的其他人
            if (!ch.equals(channel)) {
                System.out.println("["+channel.remoteAddress()+"] : " + s +"\n");
                ch.writeAndFlush("["+channel.remoteAddress()+"] : " + s +"\n");
            }
        });
    }

    /**
     * channel处于活跃状态
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "上线");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "离线");
    }

    /**
     * 断开链接
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        channelGroup.writeAndFlush("[客户端]" + ctx.channel().remoteAddress() + "下线");
        System.out.println("[客户端]" + ctx.channel().remoteAddress() + "下线");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.toString());
        ctx.close();
    }
}
